package com.abu.server.utils;

import com.abu.server.mapper.FileMapper;
import com.abu.server.pojo.FileEntity;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.UUID;

@Data
@Component
@ConfigurationProperties(prefix = "ali.oss")
public class FileOperationTemplate {

    @Autowired
    private FileMapper fileMapper;

    private String accessKeyId;

    private String accessKeySecret;

    private String endpoint;

    private String bucketName;

    public HashMap<String, String> toUpload(MultipartFile file) throws IOException {
//        创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        1. 命名文件夹名字
        String fileFolder = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        2. 重新命名文件
        String uuid = UUID.randomUUID().toString();
//        3. 执行上传
        ossClient.putObject(bucketName, fileFolder + "/" + uuid, file.getInputStream());
//        4. 获取文件上传后的地址
//        https://upload-test-01.oss-cn-beijing.aliyuncs.com/20210406/e2367546-63a9-4848-92b9-aec1cfb3f738
        String fileUrl = "https://" + bucketName + "." + endpoint + "/" + fileFolder + "/" + uuid;
//        5. 关闭OSSClient。
        ossClient.shutdown();
//        6.返回结果
        HashMap<String, String> data = new HashMap<>(2);
        data.put("url", fileUrl);
        data.put("uuid", uuid);
        return data;
    }

    public String downLoadFile(String objectName) throws IOException {
//      创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

//      根据uuid查询数据库获取时间(文件目录)
        FileEntity fileEntity = this.fileMapper.selectOne(new QueryWrapper<FileEntity>().eq("uuid", objectName).select("update_time"));
        LocalDateTime updateTime = fileEntity.getUpdateTime();
        String updateTimeStr = updateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        获取真正的文件名字（文件夹/文件名）
        String realFileName = updateTimeStr+"/"+objectName;

//      ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, realFileName);

//      读取文件内容。
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
        StringBuilder builder = new StringBuilder();
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            builder.append(line);
        }
// 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
        reader.close();

// 关闭OSSClient。
        ossClient.shutdown();
        return builder.toString();
    }

}
